package fanshe.first.demo04;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Mr.ma
 * @since 2022/10/27 16:14
 * 获取反射类中的方法，方法如下：
 *      getMethod()：获取本类及父类中的所有公开方法
 *      getMethods()：获取本类及父类中的指定公开方法
 *      getDeclaredMethod()：获取本类中的指定方法（含私有方法）
 *      getDeclaredMethods()：获取本类中的所有方法（含私有方法）
 **/
public class Test04 {
    public static void main(String[] args) throws Exception {
        Animal cat = new Cat();
//        doSome(cat);
        doOther(cat);
    }
    public static void doSome(Animal animal) throws Exception{
        Class<? extends Animal> aClass = animal.getClass();
        Method eat = aClass.getMethod("eat");
        System.out.println("eat = " + eat);
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            System.out.println("method = " + method.getName());
        }
        Method play = aClass.getDeclaredMethod("play");
        System.out.println("play = " + play);
        Method[] classDeclaredMethods = aClass.getDeclaredMethods();
        for (Method classDeclaredMethod : classDeclaredMethods) {
            System.out.println("classDeclaredMethod = " + classDeclaredMethod.getName());
        }
    }
    public static void doOther(Animal animal) throws Exception{
        Class<? extends Animal> aClass = animal.getClass();
        Method drink = aClass.getMethod("drink");
        Object invoke = drink.invoke(animal);
        System.out.println("invoke = " + invoke);

        Method play = aClass.getDeclaredMethod("play",String.class);
        play.setAccessible(true);
        Object invoke1 = play.invoke(animal,"网球");
        System.out.println("invoke1 = " + invoke1);
    }
}
class Cat extends Animal{
    @Override
    public void eat(){
        System.out.println("Cat=========eat");
    }
    private String play(String feel){
        System.out.println("Cat=========play");
        System.out.println("toy = " + feel);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }
    public String drink(){
        System.out.println("Cat=========drink");
        return "开森";
    }
}
class Animal{
    public void eat(){
        System.out.println("Animal=========eat");
    }
    private void sleep(){
        System.out.println("Animal=========sleep");
    }
}
